﻿using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChromeWebTool
{
    public class WebDriverHelper
    {

        static IWebDriver webDriver;

        public static void Open(string userNameStr, string passwordStr, string keyCodeStr)
        {
            if (webDriver == null)
            {
                webDriver = new ChromeDriver();
            }
            webDriver.Navigate().GoToUrl("https://cloud-kfs.htsc.com.cn/#/");

            //// 使用 JavaScript 等待页面完全加载
            //var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(3));
            //wait.Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));

            //wait.Until(ExpectedConditions.ElementExists(By.Id("elementId"))); // 等待元素存在
            //wait.Until(ExpectedConditions.ElementIsVisible(By.Id("elementId"))); // 等待元素可见


            var userNameEle = webDriver.FindElement(By.XPath("//*[@id=\"username\"]"));
            var passwordEle = webDriver.FindElement(By.XPath("//*[@id=\"password\"]"));
            var keyCodeEle = webDriver.FindElement(By.XPath("//*[@placeholder=\"令牌\"]"));
            var loginEle = webDriver.FindElement(By.XPath("//*[@id=\"login\"]"));
            userNameEle.Clear();
            passwordEle.Clear();
            keyCodeEle.Clear();
            userNameEle.SendKeys(userNameStr);
            passwordEle.SendKeys(passwordStr);
            keyCodeEle.SendKeys(keyCodeStr);

            loginEle.Click();
            //var DownLoadEle = webDriver.FindElement(By.XPath("//*[@id=\"app\"]/div/section/div[1]/ul/li"));
            //DownLoadEle.Click();
        }

        public static void Dispose()
        {
            if (webDriver != null)
            {
                webDriver.Dispose();
                webDriver = null;
            }
        }
    }
}
